
goog.provide('esn.FacebookApi');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.json');


/**
 * @constructor
 */
esn.FacebookApi = function() {
  this.loginCallbackQueue_ = [];
};

esn.FacebookApi.APP_ID = '201186189949808';

/**
 * @type {Object}
 * @private
 */
esn.FacebookApi.prototype.session_;

esn.FacebookApi.prototype.getLoginStatus = function(callback) {
  FB.getLoginStatus(goog.bind(this.getLoginStatusResponse_, this, callback));
};

esn.FacebookApi.prototype.getLoginStatusResponse_ = function(callback,
    response) {
  if ('authResponse' in response && response['authResponse'] != null) {
    this.session_ = response['authResponse'];
  }
  callback();
};

esn.FacebookApi.prototype.login = function(callback) {
  if (!this.session_) {
    this.loginCallbackQueue_.push(callback);
    // Only login on the first call (other calls should wait for the user to
    // log in).
    if (this.loginCallbackQueue_.length == 1) {
      FB.login(goog.bind(this.loginResponse_, this));
    }
  } else {
    callback();
  }
};

esn.FacebookApi.prototype.loginResponse_ = function(response) {
  if ('authResponse' in response && response['authResponse'] != null) {
    this.session_ = response['authResponse'];
    this.completeQueuedCallbacks_();
  } else {
    window.console.log('Could not log in the user.');
  }
};

esn.FacebookApi.prototype.logout = function(opt_callback) {
  FB.logout(function(response) {
    window.console.log(response)
    if (opt_callback) {
      opt_callback(response);
    }
  });
};

esn.FacebookApi.prototype.completeQueuedCallbacks_ = function() {
  goog.array.forEach(this.loginCallbackQueue_, function(callback) {
    callback();
  }, this);
  this.loginCallbackQueue_ = [];
};

esn.FacebookApi.prototype.getAccessToken_ = function() {
  if (this.session_) {
    return this.session_['accessToken'];
  }
  goog.asserts.fail('Facebook session has not been initialized.')
};

esn.FacebookApi.prototype.getProfile = function(callback) {
  this.login(goog.bind(function() {
    FB.api('/me', callback);
  }, this));
};

esn.FacebookApi.prototype.getFriendList = function(callback) {
  var friendFields = [
    'id',
    'name',
    'first_name',
    'last_name',
    'gender'
  ];
  this.login(goog.bind(function() {
    FB.api('/me/friends', {'fields': friendFields.join(',')},
        goog.bind(this.getFriendListResponse_, this, callback));
  }, this));
};

esn.FacebookApi.prototype.getFriendListResponse_ = function(callback,
    response) {
  if ('data' in response) {
    callback(response['data']);
  } else {
    callback(null);
  }
};


goog.exportSymbol('esn.FacebookApi.APP_ID', esn.FacebookApi.APP_ID);
